package scatter.copy.relative.path;

import com.google.common.base.Strings;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.util.Objects;

/**
 * 复制相对于当前打开文件的相对路径
 */
public class CopyRelativePathAction extends AnAction {

    private static final String SAME_LEVEL = "./";
    private static final String PARENT_LEVEL = "../";
    private static final String SPLASH = "/";


    @Override
    public void actionPerformed(AnActionEvent e) {


        // 右键选中的文件
        VirtualFile virtualFile = contextFile(e);
        // 已打开的文件操作
        VirtualFile editorFile = editorFile(e);
        // 如果没有打开文件不复制
        if (editorFile == null || virtualFile == null){
            return;
        }

        String virtualFileCanonicalPath = virtualFile.getCanonicalPath();

        String editorFileCanonicalPath = editorFile.getCanonicalPath();
        // 定义一个处理结果
        String result = null;

        if (Objects.equals(virtualFileCanonicalPath,editorFileCanonicalPath)) {
            result = SAME_LEVEL + virtualFile.getName();
        }else {

            // 获取共同前缀
            String commonPrefix = Strings.commonPrefix(virtualFileCanonicalPath, editorFileCanonicalPath);
            // 如果没有相同前缀,或者相同前缀只是一个splash则表示没有相对路径，直接返回
            if (StringUtils.isEmpty(commonPrefix) || StringUtils.equals(SPLASH,commonPrefix)) {
                return;
            }
            virtualFileCanonicalPath = virtualFileCanonicalPath.substring(commonPrefix.length());
            editorFileCanonicalPath = editorFileCanonicalPath.substring(commonPrefix.length());
             // 有可能会有互相包含的关系，如果有肯定有一个会空
            if (StringUtils.isAnyEmpty(virtualFileCanonicalPath,editorFileCanonicalPath)) {
                return;
            }
            // 计算相对层级
            String[] split = editorFileCanonicalPath.split(SPLASH);
            StringBuffer sb = new StringBuffer();

            if (split.length == 1) {
                sb.append(SAME_LEVEL);
            }else {
                for (int i = 1; i < split.length; i++) {
                    sb.append(PARENT_LEVEL);
                }
            }
            sb.append(virtualFileCanonicalPath);
            result = sb.toString();
        }

        if (result != null) {
            setClipboardString(result);
        }
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        e.getPresentation().setVisible(contextFile(e) != null && editorFile(e) != null);
    }

    /**
     * 获取右键选中的文件
     * @param e
     * @return
     */
    public static VirtualFile contextFile(AnActionEvent e) {
        VirtualFile virtualFile = e.getData(CommonDataKeys.VIRTUAL_FILE);
        return virtualFile;
    }

    /**
     * 获取已打开的选中文件
     * @param e
     * @return
     */
    public static VirtualFile editorFile(AnActionEvent e) {
        Project project = e.getProject();
        FileEditor selectedEditor = FileEditorManager.getInstance(project).getSelectedEditor();
        if (selectedEditor == null) {
            return null;
        }

        // 打开的文件
        VirtualFile editorFile = selectedEditor.getFile();
        if (editorFile == null) {
            return null;
        }
        return editorFile;
    }
    /**
     * 将文件放到剪切板
     * @param text
     */
    public static void setClipboardString(String text) {
        // 封装文本内容
        Transferable trans = new StringSelection(text);
        // 把文本内容设置到系统剪贴板
        CopyPasteManager.getInstance().setContents(trans);
    }
}
